<template>
  <div>
    <el-form
      :model="formData"
      :rules="formRules"
      ref="formData"
      label-position="top"
      label-width="100px"
      v-loading="loading"
      class="jobForm"
    >
      <el-card class="box-card" style="margin-top: 0;">
        <div class="text item">
          <div class="cont_title" v-if="isEdit">编辑作业</div>
          <div class="cont_title" v-else>新增作业</div>
          <el-button class="come-back" icon="el-icon-back" size="small" type="text" @click="goBack">返回</el-button>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="作业名称" prop="workName">
                <el-input
                  ref="workName"
                  v-model.trim="formData.workName"
                  placeholder="请填写30字以内的名称"
                  clearable
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="timeStyle">
              <el-form-item label="提交作业起止时间" prop="startTime">
                <el-date-picker
                  ref="startTime"
                  v-model="formData.startTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  class="date_picker"
                  placeholder="选择开始时间"
                  :popper-append-to-body="false"
                  :picker-options="pickerOptions1"
                  @change="datePickerChange(1,$event)"
                >
                </el-date-picker>
              </el-form-item>
              <div class="zhi">至</div>
              <el-form-item label=" " class="no_label" prop="endTime">
                <el-date-picker
                  ref="endTime"
                  v-model="formData.endTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  class="date_picker"
                  placeholder="选择结束时间"
                  :popper-append-to-body="false"
                  :picker-options="pickerOptions2"
                  @change="datePickerChange(2,$event)"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="作业内容" prop="workContext">
                <tinymce-editor
                  ref="workContext"
                  :isEdit="true"
                  :editValue="formData.workContext"
                  @changeEditor="changeEditor"
                ></tinymce-editor>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="相关附件" prop="systemLogo">
                <div class="fj_info">注：支持文件类型有word、pdf、excel、ppt、png、jpg、jpeg。</div>
                <div class="upload_box">
                  <div class="img_list" v-for="(item, index) in fileList" :key="index">
                    <div>
                      <el-image :src="fileImg"></el-image>
                      <div class="item_name">{{item.name}}</div>
                      <div class="item_remove" @click="handleRemove(item)">删除</div>
                    </div>
                  </div>

                  <el-upload
                    ref="systemLogo"
                    name="multipartFile"
                    :action="imgAction"
                    :headers="headers"
                    :file-list="fileList"
                    :disabled="upLoading"
                    list-type="picture-card"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-progress="handleProgress"
                    :on-success="handleSuccess">
                    <i v-if="!upLoading" class="el-icon-plus"></i>
                    <i v-if="upLoading" class="el-icon-loading"></i>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item class="btn">
          <el-button type="primary" @click="confirm">发布作业</el-button>
        </el-form-item>
      </el-card>
    </el-form>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import {getToken} from "@/utils/auth";
  import {CreateJob, EditJob, GetJobInfo} from "@/api/campSystem/campOper";
  import TinymceEditor from "@/components/CampSystem/CampOper/CampTiny";
  import fileImg from "@/assets/images/file_img.png";

  export default {
    name: "JobForm",
    props: {
      isEditFu: [Boolean]
    },
    components: {TinymceEditor},
    data() {
      return {
        upLoading: false,
        fileImg: fileImg,
        isEdit: this.isEditFu,
        jobId: null,
        loading: false,
        fileList: [],
        formData: {
          campId: null,
          workName: null,
          startTime: null,
          endTime: null,
          workContext: null,
          enclosureUrl: null,
        },
        formRules: {
          workName: [
            {required: true, message: '请输入作业名称', trigger: 'blur'},
            {max: 30, message: '长度在30个字符以内', trigger: 'blur'}
          ],
          startTime: [
            {required: true, message: '请选择开始时间', trigger: 'change'},
          ],
          endTime: [
            {required: true, message: '请选择结束时间', trigger: 'change'}
          ],
          workContext: [
            {required: true, message: '请输入作业内容', trigger: 'blur'}
          ]
        },
        pickerOptions1: {},
        pickerOptions2: {},
        // 上传图片请求头
        headers: {
          Authorization: "Bearer " + getToken()
        },
        imgAction: process.env.VUE_APP_BASE_API + "/modules-campsite/teacher/UploadWork",
      };
    },
    created() {
      this.formData.campId = this.$route.query.id;
      if (this.isEditFu) {
        let jobId = Cookies.get('camp_job_id');
        if (jobId) {
          this.jobId = jobId;
        }
        this.getInfo()
      } else {
        let enclosureUrl = localStorage.getItem('job_info_enclosureUrl_null');
        if (enclosureUrl) {
          // 缓存文件
          this.formData.enclosureUrl = enclosureUrl;
        }
        let url = this.formData.enclosureUrl;
        if (this.formData.enclosureUrl) {
          let arr = url.split(',');
          arr.forEach(item => {
            this.fileList.push({
              url: item,
              name: item.split('work/')[1],
              status: 'success'
            })
          })
        }
      }
    },
    methods: {
      // 设置时间向下范围
      setPickerOptionDown(val) {
        return {
          selectableRange: '00:00:00 - 23:59:59',
          disabledDate(date) {
            return date.getTime() < new Date(val).setHours(0, 0, 0, 0)
          }
        }
      },
      datePickerChange(type, val) {
        if (type == 1) {
          this.formData.endTime = null;
          this.pickerOptions2 = this.setPickerOptionDown(val);
        }
      },
      // 获取指定作业详情
      getInfo() {
        this.loading = true;
        GetJobInfo(this.jobId)
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              this.loading = false;
              return this.msgError(response.msg);
            }
            this.loading = false;
            this.formData = response.data;
            let enclosureUrl = localStorage.getItem('job_info_enclosureUrl_' + this.jobId);
            if (enclosureUrl) {
              // 缓存文件
              this.formData.enclosureUrl = enclosureUrl;
            }
            let url = this.formData.enclosureUrl;
            if (this.formData.enclosureUrl) {
              let arr = url.split(',');
              arr.forEach(item => {
                this.fileList.push({
                  url: item,
                  name: item.split('work/')[1],
                  status: 'success'
                })
              })
            }
          })
          .catch(error => {
            console.log(error);
            this.loading = false;
          });
      },
      // 返回按钮
      goBack() {
        this.$emit('closeForm', '1')
      },
      // 滚动到固定地方
      scrollView(object) {
        for (let i in object) {
          if (!i) {
            continue;
          }
          let dom = this.$refs[i];
          if (!dom) {
            continue;
          }
          // 这里是针对遍历的情况（多个输入框），取值为数组
          if (Object.prototype.toString.call(dom) !== "[object Object]") {
            dom = dom[0];
          }
          // 第一种方法（包含动画效果）
          dom.$el.scrollIntoView({
            // 滚动到指定节点
            // 值有start,center,end，nearest，当前显示在视图区域中间
            block: "center",
            // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            behavior: "smooth",
          });
          this.dialogVisibleFu = true;
          break; // 因为我们只需要检测一项,所以就可以跳出循环了
        }
      },
      // 发布作业按钮
      confirm() {
        this.loading = true;
        this.$refs['formData'].validate((valid, object) => {
          if (!valid) {
            this.scrollView(object);
            return this.loading = false;
          }
          if (this.isEdit) {
            let obj = {
              campId: this.formData.campId,
              id: this.formData.id,
              workName: this.formData.workName,
              startTime: this.formData.startTime,
              endTime: this.formData.endTime,
              workContext: this.formData.workContext,
              enclosureUrl: this.formData.enclosureUrl
            }
            EditJob(obj)
              .then(response => {
                console.log(response);
                if (response.code != 200) {
                  this.loading = false;
                  return this.msgError(response.msg);
                }
                this.loading = false;
                this.msgSuccess(response.msg);
                this.$emit('closeForm', '1');
              })
              .catch(error => {
                console.log(error);
                this.loading = false;
              });
          } else {
            CreateJob(this.formData)
              .then(response => {
                console.log(response);
                if (response.code != 200) {
                  this.loading = false;
                  return this.msgError(response.msg);
                }
                this.loading = false;
                this.msgSuccess(response.msg);
                this.$emit('closeForm', '1');
              })
              .catch(error => {
                console.log(error);
                this.loading = false;
              });
          }
        });
      },
      // 验证上传图片格式
      valiImgType(str) {
        if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(str)) {
          return true;
        }
        return false;
      },
      // 删除文件
      handleRemove(data) {
        this.fileList = this.fileList.filter(item => {
          return item != data;
        })
        this.formData.enclosureUrl = this.fileList.map(item => {
          return item.url
        }).join(',');
        if (this.isEdit) {
          localStorage.setItem('job_info_enclosureUrl_' + this.jobId, this.formData.enclosureUrl);
        } else {
          localStorage.setItem('job_info_enclosureUrl_null', this.formData.enclosureUrl);
        }
      },
      // 文件上传成功时的钩子
      handleSuccess(res, file, fileList) {
        if (res.code != 200) {
          this.upLoading = false;
          return this.msgError(res.msg);
        }
        let length = this.fileList.length;
        this.fileList[length] = {
          status: 'success',
          name: res.msg.split('work/')[1],
          url: res.msg
        }
        this.formData.enclosureUrl = this.fileList.map(item => {
          return item.url
        }).join(',');
        if (this.isEdit) {
          localStorage.setItem('job_info_enclosureUrl_' + this.jobId, this.formData.enclosureUrl);
        } else {
          localStorage.setItem('job_info_enclosureUrl_null', this.formData.enclosureUrl);
        }

        this.upLoading = false;
        this.msgSuccess('上传成功');
      },
      handleProgress(event, file, fileList) {
        this.upLoading = true;
      },
      // 上传文件之前的钩子
      beforeUpload(file) {
        const isLt10M = file.size / 1024 / 1024 <= 100;

        if (!isLt10M) {
          this.$message.error('上传的附件大小不能超过 100M!');
          return false;
        }
        return isLt10M;
      },
      // 子组件值改变，父组件值相应改变(子组件触发)
      changeEditor(val) {
        this.formData.workContext = val;
      },
    },
    destroyed() {
      if (this.isEdit) {
        localStorage.removeItem('job_info_enclosureUrl_' + this.jobId);
      } else {
        localStorage.removeItem('job_info_enclosureUrl_null');
      }
    },
    watch: {
      isEditFu() {
        this.isEdit = this.isEditFu;
      },
    }
  }
</script>

<style lang="scss">
  @import "@/assets/styles/card.scss";
  @import "@/assets/styles/campCommon.scss";

  .come-back {
    position: absolute;
    top: 20px;
    font-weight: bold;

    .el-icon-back {
      font-weight: bold;
    }
  }

  .jobForm {
    padding: 0 !important;

    .cont_title {
      position: relative;
      height: 24px;
      line-height: 24px;
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #12141C;
      margin-bottom: 30px;
      text-align: center;
    }

    .fj_info {
      line-height: 24px;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
    }

    .el-form-item {
      position: relative;

      .el-form-item__label {
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #12141C;
      }

      .el-form-item__content {
        text-align: left !important;

        .el-input, .el-date-editor {
          height: 40px;
          line-height: 40px;

          .el-input__icon,
          .el-range-separator {
            line-height: 32px;
          }

          .el-input__inner {
            height: 40px;
            line-height: 40px;
            border-radius: 4px;
            border: 1px solid #E1E3E6;

            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 500;

            &::-webkit-input-placeholder {
              color: #BCC2CA;
            }

            &::-ms-input-placeholder {
              color: #BCC2CA;
            }
          }
        }

        .upload_box {
          margin-top: 10px;

          .img_list {
            position: relative;
            float: left;
            width: 160px;
            height: 120px;
            text-align: center;
            background: transparent;
            border-radius: 4px;
            border: 2px dashed #E1E3E6;
            margin: 0 8px 8px 0;
            padding: 5px;
            display: flex;
            flex-flow: column;
            justify-content: center;
            align-items: center;

            > div {
              width: 100%;

              .el-image {
                width: 30px;
                height: 30px;
                min-height: 30px;
                display: block;
                margin: 0 auto;
                border: 0;

                img {
                  width: auto;
                  height: auto;
                  max-width: 100% !important;
                  max-height: 100% !important;
                }
              }

              .item_name {
                font-size: 12px;
                color: #999999;
                line-height: 16px;
                word-wrap: break-word;
                margin: 5px 0 10px;
              }

              .item_remove {
                width: 40px;
                font-size: 12px;
                color: #999999;
                font-weight: bold;
                line-height: 16px;
                margin: 0 auto;

                &:hover {
                  cursor: pointer;
                  color: red;
                }
              }
            }
          }

          .el-upload {
            width: 160px !important;
            height: 120px !important;
            line-height: 120px !important;
            background: transparent;
            border-radius: 4px;
            border: 2px dashed #E1E3E6;
            text-align: center !important;
          }
        }
      }

      /*底部按钮样式*/
      &.btn {
        padding: 50px 0;

        .el-form-item__content {
          text-align: center !important;
        }

        .el-button {
          width: 200px;
          height: 50px;
          background: #4D75F3;
          border-radius: 4px;
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #FFFFFF;

          span {
            font-size: 14px !important;
          }
        }
      }

      /*去除*号*/
      &.no_label {
        .el-form-item__label:before {
          content: '' !important;
        }
      }
    }

    .timeStyle {
      display: flex;
      flex-flow: row;

      .el-form-item {
        flex: 1;
      }

      .zhi {
        padding: 42px 15px 22px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #656872;
      }
    }
  }

</style>


